<template>
    <div class="app-container">
        <div style="position: sticky;top: 0;">
            <el-row :gutter="10">
                <el-col :span="6">{{ localTplMetdata.名称 }}</el-col>
                <el-col :span="6">{{ localTplMetdata.名称 }}</el-col>
                <el-col :span="6">{{ outerTplMetdata.名称 }}</el-col>
                <el-col></el-col>
            </el-row>

            <el-row :gutter="10">
                <el-col :span="6">

                    <p>
                        <el-checkbox v-model="onlyDif" @change="onChange">只看差异</el-checkbox>
                    </p>
                </el-col>
                <el-col :span="6">我院模板标杆：{{ 本院模板标杆 }}</el-col>
                <el-col :span="6">外院模板标杆：{{ 外院模板标杆 }}</el-col>
                <el-col :span="6">
                    <el-button type="danger" @click="refresh" round>刷新</el-button>
                    <!-- <el-button type="danger" @click="allModel()" round>批量一致</el-button> -->

                    <el-dropdown style="margin-left: 5px;" @command="handleCommand">
                        <el-button type="danger" round>
                            操作<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="检验检查">检验检查批量一致</el-dropdown-item>
                            <el-dropdown-item divided command="所有">所有项目批量一致</el-dropdown-item>
                            <el-dropdown-item divided command="必选">一键必选</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>

                </el-col>
            </el-row>

            <el-row>
                <el-col :span="5">
                    我院模板药品小计：{{ 本院药品小计 }}
                </el-col>
                <el-col :span="5">
                    参考模板药品小计：{{ 外院药品小计 }}
                </el-col>
                <el-col :span="3">
                    模板有：<span class="tshh">{{ 模板有 }}</span>
                </el-col>
                <el-col :span="3">
                    模板无:<span class="tshh">{{ 模板无 }}</span>
                </el-col>
                <el-col :span="3">
                    模板必选：<span class="tshh">{{ 模板必选 }}</span>
                </el-col>
                <el-col :span="3">
                    模板备选：<span class="tshh">{{ 模板备选 }}</span>
                </el-col>
            </el-row>
        </div>
        <el-row>
            <el-table :data="all项目" border style="width: 100%" height="800" v-loading="loading"
                :row-class-name="tableRowClassName">
                <el-table-column prop="类别" width="100" label="类别">
                </el-table-column>
                <el-table-column prop="项目名称" label="项目名称">
                </el-table-column>
                <el-table-column label="本院模板" prop="本院">
                    <!-- <template slot-scope="{ row }">
                        {{ 模板对比('本院', row) }}
                    </template> -->
                </el-table-column>
                <el-table-column label="外院参考模板" prop="外院">
                    <!-- <template slot-scope="{ row }">
                        {{ 模板对比('外院', row) }}
                    </template> -->
                </el-table-column>
                <el-table-column label="操作" prop="本院">
                    <template slot-scope="{ row }">
                        <el-link type="primary" v-if="!row.group" @click="$event => modify(row, $event)">{{ row.本院 == row.外院
                            ? "已一致" :
                            "更新为一致" }}</el-link>
                        <span v-else>{{ row.data }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { LsFiles, DestoryFile } from "@/api/commonApi";
import {
    tplDetail,
    saveTpl,
    drgNames,
    drgInfo,
    cnHops,
    saveTplDrg,
    drgweightbyid,
    searchListInKey,
    searchListInVal,
    saveTplDetail
} from "@/api/PathTemplate";
import { delTpls, tplls, copyTpl, GetTplById } from "@/api/pathway";
import request from "@/utils/request";
import { UserModule } from "@/store/modules/user";
import axios from 'axios'
import { throttleAfterHits } from "handsontable/helpers";
import { Row } from "element-ui";
import { count, time } from "console";
@Component({
    // components: { index },
    name: "templdif",
})
export default class extends Vue {
    private 模板对比ID = 'b2aebe8f-f84f-c09e-8959-c5c2a8f248e9';
    //本院模板ID
    private templid = '';
    //外院模板文件
    private templfile = '';
    //本院模板数据、元数据
    private localTplMetdata: any = {};
    private localTplData: Array<any> = [];

    //外院模板数据、元数据
    private outerTplMetdata: any = {};
    private outerTplData: Array<any> = [];

    //只看差异
    private onlyDif: boolean = false;

    private 模板有 = '●';
    private 模板无 = '✘';
    private 模板必选 = '●●';
    private 模板备选 = '―';
    private downLoadUrl = `${(<any>window).MyConf.APISERVICE}/files/`;

    private loading = true;
    private async created() {
        this.refresh();
    }

    private async refresh() {
        this.loading = true;
        // this.onlyDif = false;
        this.templid = this.$route.query.tid;
        this.templfile = this.$route.query.url;
        await this.本院模板();
        await this.外院模板();
        this.初始化界面();
        this.loading = false;
    }

    private tableRowClassName(p: any) {
        if (p.row.group) return 'groupsummary'
        return '';
    }
    private 本院模板标杆: any = 0;
    private 外院模板标杆: any = 0;
    private async onChange() {
        await this.refresh();
        if (this.onlyDif) {
            this.all项目 = this.all项目.filter(it => it.本院 !== it.外院);
        } else this.初始化界面();
    }

    private uuid() {
        var s: any = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }
    private async handleCommand(cmd: any) {
        let ls: any = [];
        if (cmd == '检验检查') {
            let ts = this.all项目.filter((it: any) => it.类别 == '检验' || it.类别 == '检查');
            for (let row of ts) {
                if (!row.group) {
                    let d = await this.modify(row, null, true);
                    ls.push(d);
                }
            }
        } else if (cmd == '所有') {
            for (var row of this.all项目) {
                if (!row.group) {
                    let d = await this.modify(row, null, true);
                    ls.push(d);
                }
            }
        } else if (cmd == '必选') {
            let ts = this.all项目.filter((it: any) => it.外院 == this.模板必选);
            for (var row of ts) {
                if (!row.group) {
                    let d = await this.modify(row, null, true);
                    ls.push(d);
                }
            }
        }

        ls = ls.filter((it: any) => it);

        if (ls.length > 0) {
            this.$confirm(`${ls.length}更新为与院外参考模板一致？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(async () => {
                this.loading = true;
                let d = await saveTplDetail({ json: JSON.stringify(ls), t: (new Date()).getTime() }).finally(() => {
                    this.loading = false;
                    this.refresh();
                });
            }).finally(() => {
                this.loading = false;
            });
        }

    }
    // private allModel() {
    //     this.$confirm("是否全部更新为与院外参考模板一致？", "提示", {
    //         confirmButtonText: "确定",
    //         cancelButtonText: "取消",
    //         type: "warning",
    //     })
    //         .then(async () => {
    //             let ls = [];
    //             for (var row of this.all项目) {
    //                 if (!row.group) {
    //                     let d = await this.modify(row, null, true);
    //                     ls.push(d);
    //                 }
    //             }
    //             ls = ls.filter(it => it);
    //             if (ls.length > 0) {
    //                 this.loading = true;
    //                 let d = await saveTplDetail({ json: JSON.stringify(ls), t: (new Date()).getTime() }).finally(() => {
    //                     this.loading = false;
    //                     this.refresh();
    //                 });
    //             }



    //         })

    // }
    private async modify(row: any, $event: any, isbatch: boolean = false) {

        if (row.本院 == row.外院) return;
        //1.判断要进行的操作
        let op = 'update';
        let dataItem = row['本院-dataItem'];

        if (row.外院 == this.模板无) {
            op = 'del';

        } else if (row.本院 == this.模板无) {
            op = 'insert'
            dataItem = row['外院-dataItem'];
            dataItem.序号 = this.all项目.indexOf(row);
            dataItem.从表ID = this.uuid();
            dataItem.明细ID = dataItem.从表ID;
            // dataItem.id = dataItem.从表ID;
        } else if (row.本院 !== row.外院) {
            op = 'update';
            let 外院dataItem = row['外院-dataItem']
            dataItem.缺省 = 外院dataItem.缺省;
            dataItem.选择属性 = 外院dataItem.选择属性;
            // dataItem.id = dataItem.从表ID
            dataItem.数量 = 外院dataItem.数量;
            if (dataItem.缺省 && !dataItem.单价)
                dataItem.单价 = 外院dataItem.单价;
        }
        dataItem.id = dataItem.从表ID || dataItem.明细ID;

        dataItem.执行性质 = dataItem.选择属性 == '必选' ? 1 : 0;
        dataItem.模板id = this.templid;
        dataItem.版本ID = this.templid;
        dataItem.op = op;
        this.loading = true;
        if (isbatch) {
            return dataItem;
        }
        let d = await saveTplDetail({ json: JSON.stringify([dataItem]), op: op, t: (new Date()).getTime() });
        this.loading = false;
        row.本院 = row.外院
    }

    private 本院药品小计: any = 0;
    private 外院药品小计: any = 0;
    private 初始化界面() {
        let allProjects = [...this.localTplData];

        this.本院模板标杆 = this.localTplData.map(it => (it.单价 * it.数量) || 0).reduce((a, b) => a + b).toFixed(2);
        this.外院模板标杆 = this.outerTplData.map(it => (it.单价 * it.数量) || 0).reduce((a, b) => a + b).toFixed(2);

        this.本院药品小计 = this.localTplData.filter(it => it.类别 == '药品').map(it => (it.单价 * it.数量) || 0).reduce((a, b) => a + b).toFixed(2);
        this.外院药品小计 = this.outerTplData.filter(it => it.类别 == '药品').map(it => (it.单价 * it.数量) || 0).reduce((a, b) => a + b).toFixed(2);


        allProjects.push(...this.outerTplData);
        allProjects = allProjects.map(it => ({ 项目名称: it.项目名称, 类别: it.类别 }));
        let o = {};
        allProjects.forEach(it => {
            let k = `${it.类别}##${it.项目名称}`
            o[k] = it;
        })
        let allProjects2 = [];
        Object.keys(o).forEach(k => {
            o[k].外院 = o[k].本院 = '';
            allProjects2.push(o[k])
        })

        let sortDict = {
            药品: 1,
            检验: 2,
            检查: 3,
            手术: 4,
            治疗: 5,
            耗材: 6,
            其他: 7
        }
        Object.keys(sortDict).forEach((k: any) => {
            let ts = this.localTplData.filter(it => it.类别 == k).map(it => (it.单价 * it.数量) || 0);
            if (ts.length > 0) {
                let sum = this.localTplData.filter(it => it.类别 == k).map(it => (it.单价 * it.数量) || 0)?.reduce((a, b) => a + b);
                allProjects2.push({ 类别: k, data: sum.toFixed(2), group: true, 本院: "___", 外院: "__" });
            }
        })
        allProjects2 = allProjects2.sort((a, b) => {
            return (sortDict[a.类别] || 100) - (sortDict[b.类别] || 100)
        })
        this.localTplData.forEach(it => {
            let k = `${it.类别}-${it.项目名称}`;
            if (!this.projectMap.本院[k]) this.projectMap.本院[k] = [];
            this.projectMap.本院[k].push(it)
        })
        this.outerTplData.forEach(it => {
            let k = `${it.类别}-${it.项目名称}`;
            if (!this.projectMap.外院[k]) this.projectMap.外院[k] = [];
            this.projectMap.外院[k].push(it)
        })
        allProjects2.forEach(it => {
            this.模板对比('本院', it);
            this.模板对比('外院', it);
        })
        this.all项目 = allProjects2;
    }
    private all项目: Array<any> = [];
    private files: Array<any> = [];
    private projectMap: any = { '本院': {}, '外院': {} };

    private 模板对比(t: string, row: any) {

        if (row.group) return '';

        let 当前数据集 = this.projectMap[t];
        let k = `${row.类别}-${row.项目名称}`;
        let items = 当前数据集[k];
        let result = this.模板有;
        let dataItem = {};
        if (items) {
            let findLs = items.filter(it => it.类别 == row.类别 && it.项目名称 == row.项目名称)
            dataItem = findLs[0];
        }
        items?.forEach((it: any) => {
            it.选择属性 = (it.选择属性 || '可选')
            it.缺省 = it.数量 * it.单价 > 0
        })

        if (!items) result = this.模板无;
        else if (items.filter(it => it.选择属性 == '必选').length > 0) {
            result = this.模板必选;
            dataItem = items.filter(it => it.选择属性 == '必选')[0];
        } else if (items.filter(it => it.选择属性 == '可选' && it.缺省).length > 0) {
            result = this.模板有;
            dataItem = items.filter(it => it.选择属性 == '可选' && it.缺省)[0];
        } else if (items.filter(it => it.选择属性 == '可选').length > 0) {
            result = this.模板备选;
            dataItem = items.filter(it => it.选择属性 == '可选')[0];
            dataItem.数量 = 0;
        }
        row[t] = result;
        row[t + '-dataItem'] = dataItem;
        //return result;
    }
    private async 本院模板() {
        let tplData = await tplDetail({ tplid: this.templid });
        let tMeta = await GetTplById({ id: this.templid });
        this.localTplMetdata = tMeta.data.tpl;
        this.localTplData = tplData.data;
    }
    private async 外院模板() {
        let tPath = `${this.downLoadUrl}/${this.templfile}`
        const service = axios.create({
            baseURL: (<any>window).MyConf.APISERVICE,
            timeout: 5000 * 10
        })

        return new Promise((resolve, reject) => {
            axios.get(tPath, {
                headers: { "X-Access-Token": UserModule.token },
            }).then(res => {
                this.outerTplMetdata = res.data[0].tpl;
                this.outerTplData = res.data[0].data;
                resolve({})
            });
        })

    }
}
</script>
<style lang="scss">
.el-col {
    padding: 5px;
}

.el-checkbox__label {
    color: red;
    font-weight: bold;
}

.tshh {
    font-size: 16px !important;
    font-weight: bold;
}

.groupsummary {
    font-weight: bold;
    background-color: #C0C0C0 !important;
    font-size: 20px !important;
    color: blue;
    font-style: italic
}
</style>